import 'package:get/get.dart';
import 'package:jss_flutter/bean/barter_goods_entity.dart';
import 'package:jss_flutter/bean/goods_response_entity.dart';
import 'package:jss_flutter/http/net/http_client.dart';
import 'package:jss_flutter/http/net/http_response.dart';
import 'package:jss_flutter/utils/log_utils.dart';

import '../../app/config/route_config.dart';
import 'state.dart';

class HomeLogic extends GetxController {
  final HomeState state = HomeState();
  HttpClient dio = Get.find<HttpClient>();

  /// 可 async 拉取数据
  /// 可触发展示交互组件
  /// onInit 之后
  @override
  void onReady() {
    super.onReady();
    getBarterGoodsList();
    getGoodsList();
  }

  void getGoodsList() async {
    // goods/get_list
    var data = {
      "type": "1",
      "category_level": "0",
      "category_id": "0",
      "page": state.page.toString()
    };
    HttpResponse appResponse = await dio.post("goods/get_list", data: data);
    if (appResponse.ok) {
      var response = GoodsResponseEntity.fromJson(appResponse.data);
      if (null != response.data) {
        if (state.page.value == 1) {
          state.goodsList.clear();
        }
        state.goodsList.addAll(response.data!);
      } else {
        if (state.page.value == 1) {
          state.goodsList.clear();
        }
      }
    } else {
      LogUtils.e("==fail==${appResponse.error}");
    }
  }

  void getBarterGoodsList() async {
    // barter/goods_list
    var data = {"lat": "28.188452", "lng": "113.010063", "activity_type": "0"};

    HttpResponse appResponse = await dio.post("barter/goods_list", data: data);
    if (appResponse.ok) {
      var response = BarterGoodsEntity.fromJson(appResponse.data);
      if (null != response.data) {
        state.items.value = response.data!;
        state.offstage.value = false;
      } else {
        LogUtils.d("list empty");
        state.offstage.value = true;
      }
    } else {
      state.offstage.value = true;
      LogUtils.e("==fail==${appResponse.error}");
    }
  }

  void jumpStore() => Get.toNamed(RouteConfig.store);

  void jumpDetail(id) => Get.toNamed(RouteConfig.goodsDetail, arguments: id);
}
